import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
// import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

import config from '@/config/defaultSettings'
const DEFAULT_COLOR = localStorage.getItem('DEFAULT_COLOR')
const DEFAULT_THEME = localStorage.getItem('DEFAULT_THEME')
const DEFAULT_LAYOUT_MODE = localStorage.getItem('DEFAULT_LAYOUT_MODE')
store.commit('app/TOGGLE_COLOR', DEFAULT_COLOR || config.primaryColor)
store.commit('app/TOGGLE_THEME', DEFAULT_THEME || config.navTheme)
store.commit('app/TOGGLE_LAYOUT_MODE', DEFAULT_LAYOUT_MODE || config.layout)

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach((to, from, next) => {
  // 进度开始
  NProgress.start()

  // 设置页面标题
  document.title = getPageTitle(to.meta.title)

  // 查询是否页面处于登录状态
  // const hasToken = getToken()
  const hasToken = sessionStorage.getItem('ACCESS_TOKEN')

  if (hasToken) {
    if (to.path === '/login') {
      // 如果已经登录,跳转到首页
      next({ path: '/' })
      NProgress.done()
    } else {
      // determine whether the user has obtained his permission roles through getInfo
      // const hasRoles = store.getters.roles && store.getters.roles.length > 0
      const hasRoles = 1
      if (hasRoles) {
        next()
      } else {
        try {
          // 获取角色数据
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          // const { roles } = await store.dispatch('user/getInfo')

          // generate accessible routes map based on roles
          const accessRoutes = store.dispatch('permission/generateRoutes', [])

          // dynamically add accessible routes
          router.addRoutes(accessRoutes)

          // 确保router数组已经获取到
          // 保存路由记录
          next({ ...to, replace: true })
        } catch (error) {
          // 移除token,重新获取
          // await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token */

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
